package cn.demomaster.quickui_sample.ui.fragment.component;

import static cn.demomaster.quickaudiorecorder.AudioUtil.calculateVolume;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.media.Image;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.demomaster.quickcompat.util.ByteUtil;
import com.demomaster.quickcompat.util.DisplayUtil;
import com.demomaster.quickcompat.util.QDFileUtil;
import com.demomaster.quickcompat.widget.dialog.QuickDialog;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.demomaster.quickaudiorecorder.AudioRecorder;
import cn.demomaster.quickaudiorecorder.RecordStreamListener;
import cn.demomaster.quickaudiorecorder.view.WaveLineView;
import cn.demomaster.quickaudiorecorder.view.WaveView;
import cn.demomaster.quickaudiorecorder.view.wechat.WechatAudioRecordPopup;
import cn.demomaster.quicklogger.QdLog;
import cn.demomaster.quickpermission.QuickPermission;
import cn.demomaster.quickpermission.listener.PermissionResultCallback;
import cn.demomaster.quickrouter.fragment.QuickFragment;
import cn.demomaster.quickui.annotation.ActivityPager;
import cn.demomaster.quickui.annotation.ResType;
import cn.demomaster.quickui_sample.R;
import cn.demomaster.quickui_sample.adapter.AudioAdapter;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;


/**
 * 音频播放view
 * Squirrel桓
 * 2018/8/25
 */
@ActivityPager(name = "音频录制", preViewClass = TextView.class, resType = ResType.Resource)//,iconRes = R.drawable.ic_audio2)
public class AudioRecordFragment extends QuickFragment {

    View mView;

    @Nullable
    @Override
    public View onGenerateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_layout_audiorecord, null);
        return mView;
    }

    @Override
    public void initView(View rootView) {
        Button btn_record = rootView.findViewById(R.id.btn_record);
        btn_record.setOnTouchListener((v, event) -> {
            QuickPermission.with(getActivity()).permissions(
                   new String[]{ Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE})
                    .onGranted(new Function0<Unit>() {
                        @Override
                        public Unit invoke() {
                            showPopWindow(v, event);
                            return null;
                        }
                    }).request();
//                    .callback(new PermissionResultCallback() {
//                @Override
//                public void onPermissionsGranted(String[] permissions) {
//                    showPopWindow(v, event);
//                }
//
//                @Override
//                public void onPermissionsDenied() {
//                    Toast.makeText(mContext, "拒绝", Toast.LENGTH_LONG).show();
//                }
//            });
            //v.performClick();
            return true;
        });

        initDatas();
        initUI();
    }

    private WechatAudioRecordPopup pop = null;

    private void showPopWindow(View v, MotionEvent event) {
        int[] location = new int[2];
        v.getLocationOnScreen(location);//获取在整个屏幕内的绝对坐标
        if (pop != null && pop.isShowing()) {
            pop.setButtonLocation(location);
            pop.getTouchableViewGroup().dispatchTouchEvent(event);
            return;
        }
        pop = new WechatAudioRecordPopup(getContext());
        //pop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        //pop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        pop.setWidth(DisplayUtil.getScreenWidth(mContext));
        pop.setHeight(DisplayUtil.getScreenHeight(mContext));
        //pop.setClippingEnabled(true);
        //pop.setIsClippedToScreen(true);
        //pop.setBackgroundDrawable(new BitmapDrawable());
        pop.setBackgroundDrawable(new ColorDrawable());
        pop.setFocusable(true);
        pop.setOutsideTouchable(false);
        //pop.showAtLocation(pop.getContentView(), Gravity.BOTTOM, 0, 0);
        pop.showAtLocation(pop.getContentView(), Gravity.NO_GRAVITY, 0, 0);
        pop.setOnRecordListener(new WechatAudioRecordPopup.OnRecordListener() {
            @Override
            public void onFinish() {
                stopRecord();
            }

            @Override
            public void onCancel() {
                releaseRecord();
            }
        });
        pop.setButtonLocation(location);
        pop.getTouchableViewGroup().dispatchTouchEvent(event);

        //振動
        Vibrator vibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
        long[] patter = {0, 30, 10, 30};
        vibrator.vibrate(patter, -1);
        startRecord();
        /*startAnimation(AnimationUtils.loadAnimation(getThemeActivity(),
                R.anim.bottom_up));*/
    }

    Button btn_start_record;
    Button btn_pause_record;
    Button btn_stop_record;
    WaveView waveView;
    WaveLineView waveLineView;
    AudioRecorder audioRecorder;

    //存放的目录路径名称
    //初始化数据
    private void initDatas() {
        audioRecorder = AudioRecorder.getInstance();
        audioRecorder.setRecordStreamListener(mRecordStreamListener);
    }

    RecyclerView recyclerview_audio;
    AudioAdapter adapter;
    List<String> audioFiles = new ArrayList<>();

    //初始化UI
    private void initUI() {
        btn_start_record = mView.findViewById(R.id.btn_start_record);
        btn_start_record.setOnClickListener(v -> startRecord());
        btn_pause_record = mView.findViewById(R.id.btn_pause_record);
        btn_pause_record.setOnClickListener(v -> pauseRecord());
        btn_stop_record = mView.findViewById(R.id.btn_stop_record);
        btn_stop_record.setOnClickListener(v -> stopRecord());

        waveView = mView.findViewById(R.id.waveView);
        waveLineView = mView.findViewById(R.id.waveLineView);

        recyclerview_audio = mView.findViewById(R.id.recyclerview_audio);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext, RecyclerView.VERTICAL, false);
        recyclerview_audio.setLayoutManager(layoutManager);
        adapter = new AudioAdapter(getContext());
        adapter.setOnItemClickListener(new AudioAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                playAudio(fileOutputPath + "/" + audioFiles.get(position));
            }

            @Override
            public void onItemPreview(View view, int position, Image image) {

            }

            @Override
            public void onDelete(View view, int position) {
                QuickDialog quickDialog = new QuickDialog.Builder(mContext)
                        .create();
                quickDialog.bindView(R.id.tv_title,"确定要删除该文件吗？")
                        .bindView(R.id.tv_left,"确定", (dialog, view1, tag) -> {
                            String f = (fileOutputPath + "/" + audioFiles.get(position));
                            QdLog.e("删除：" + (fileOutputPath + "/" + audioFiles.get(position)));
                            QDFileUtil.delete(f);
                            refreshUI();
                            dialog.dismiss();
                        });
                quickDialog.show();
            }
        });
        recyclerview_audio.setAdapter(adapter);
        refreshUI();
    }

    private void playAudio(String path) {
        MediaPlayer mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //开始录音
    public void startRecord() {
        QuickPermission.with(getActivity()).permissions(new String[]{
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE})
                .onGranted(new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        if (audioRecorder.getStatus() == AudioRecorder.Status.STATUS_IDLE) {
                            audioRecorder.createAudio(getContext());
                            //audioRecorder.setOutputFilePath("");
                            //audioRecorder.setFileName("hahaha");
                        }
                        try {
                            audioRecorder.startRecord();
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        return null;
                    }
                }).request();
    }

    //结束录音
    private void stopRecord() {
        //QdToast.show(getContext(),"结束录音");
        audioRecorder.stopRecord();
        refreshUI();
    }

    String fileOutputPath;

    private void refreshUI() {
        audioFiles.clear();
        fileOutputPath = mContext.getFilesDir().getAbsolutePath() + "/wav";
        File file = new File(fileOutputPath);
        if (file.exists()) {
            if (file.isDirectory()) {
                for (File file1 : file.listFiles()) {
                    audioFiles.add(file1.getName());
                }
            }
        }
        adapter.updateList(audioFiles);
    }

    //暂停录音
    private void pauseRecord() {
        audioRecorder.pauseRecord();
    }

    //取消录音
    private void releaseRecord() {
        //QdToast.show(getContext(),"取消录音");
        audioRecorder.release();
    }

    int count = 0;
    RecordStreamListener mRecordStreamListener = new RecordStreamListener() {
        @Override
        public void onStart() {
            btn_start_record.setVisibility(View.GONE);
            btn_pause_record.setVisibility(View.VISIBLE);
            btn_stop_record.setVisibility(View.VISIBLE);
            waveLineView.startAnim();
        }

        @Override
        public void onPause() {
            btn_start_record.setVisibility(View.VISIBLE);
            btn_pause_record.setVisibility(View.GONE);
            btn_stop_record.setVisibility(View.VISIBLE);
            waveLineView.stopAnim();
        }

        @Override
        public void onStop(boolean isSuccess, String filePath) {
            mContext.runOnUiThread(() -> {
                btn_start_record.setVisibility(View.VISIBLE);
                btn_pause_record.setVisibility(View.GONE);
                btn_stop_record.setVisibility(View.GONE);
                waveLineView.stopAnim();
                refreshUI();
            });
        }

        @Override
        public void onRelease() {
            btn_start_record.setVisibility(View.VISIBLE);
            btn_pause_record.setVisibility(View.GONE);
            btn_stop_record.setVisibility(View.GONE);
            waveLineView.stopAnim();
        }

        @Override
        public void recordOfByte(byte[] data, int begin, int end) {
            ((Activity) getContext()).runOnUiThread(() -> {
                short[] data1 = ByteUtil.toShorts(data);
                for (int i = 0; i < data1.length; i += 60) {
                    waveView.addData(data1[i]);
                }

               // if (count % 1 == 0) {
                    int volume = (calculateVolume(data1));
                    double myVolume = (volume - 40) * 4;
                    //Log.d("MainActivity", "current volume=" + volume + ",myVolume=" + myVolume);
                    if (waveLineView != null) {
                        waveLineView.setVolume((int) myVolume);
                    }
                    if (pop != null) {
                        pop.setVolume(Math.max(0, volume - 40));
                    }
                    //Log.d("MainActivity", "current volume is " + volume);
                //}
                count++;
            });
        }
    };

}